from get_psndoc import get_personal_data
from commit_func import get_token
import datetime
import requests
from urllib.parse import urlencode
from langchain_core.tools import tool
from locale import currency
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# 假设get_token函数从以下模块导入，请根据实际情况调整
@tool
def qianka_get_kq(user_id: str, month: str):
    """判断用户{user_id}在本年{month}月份是否需要申请签卡, {month}格式为两位数格式字符串，如06。"""
    base_url = "http://192.168.22.92:8080/portal/api/emphelp/getDailyAttendReports"

    header = {
        "token": get_token(user_id),
    }

    # 获取当前年份
    # current_year = datetime.datetime.now().year
    current_year = 2025

    # 确保month是两位数格式
    month = month.zfill(2)
    begin_date = f"{current_year}-{month}-01"

    # 计算月份的最后一天
    if month == "12":
        next_month = "01"
        next_year = current_year + 1
    else:
        next_month = str(int(month) + 1).zfill(2)
        next_year = current_year

    # 获取下个月的第一天，然后减去一天得到当前月的最后一天
    last_day_of_month = (datetime.datetime.strptime(
        f"{next_year}-{next_month}-01", "%Y-%m-%d") - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
    end_date = last_day_of_month
    print(f"{begin_date} - {end_date}")

    params = {
        "begindate": begin_date,
        "enddate": end_date,
    }

    query_string = urlencode(params)
    url = f"{base_url}?{query_string}"

    response = requests.get(url, headers=header)

    data = response.json()

    # 判断缺勤记录
    absent_days = []
    if data.get('resultCode') == '0':
        for record in data.get('data', []):
            # 条件：工作时长为0且没有打卡记录
            if record.get('attendType') == '缺勤':
                absent_days.append(record)

    return absent_days


def qianka_post(user_id: str, empdate: list, attends: list):
    user_data = get_personal_data(user_id).get('data')
    user_name = user_data.get('username')
    pk_group = user_data.get('pk_group')
    pk_org = user_data.get('orgBipPk')
    # signreason_url = 'http://192.168.22.92:8080/portal/api/emphelp/signcard/getSignCardItem'

    # data = {
    #     "pk_group": pk_group,
    #     "pk_org": pk_org,
    #     "psncode": user_id,
    # }
    header = {
        "token": get_token(user_id),
    }

    # signreason = requests.post(signreason_url, data=data, headers=header)
    reason = '1002A2100000002QA706'

    now_date = datetime.datetime.now().strftime('%Y-%m-%d')
    url = f'http://192.168.22.92:8080/portal/api/emphelp/signcard/commit?pk_group={pk_group}'
    for i in range(len(empdate)):
        for j in range(len(check_attendance(attends[i]))):
            data = {
                "hvo": {
                    "apply_date": str(now_date),
                    "pk_group": pk_group,
                    "user_name": user_name,
                    "user_code": user_id
                },
                "bvos": [
                    {
                        "signdate": str(empdate[i]),
                        "signreason": reason,
                        "signremark": "测试",
                        "signtime": f"{empdate[i]} {check_attendance(attends[i])[j]}:00"
                    }
                ]
            }
            # print(data)
            header = {
                "token": get_token(user_id),
                "Content-Type": "application/json;charset=UTF-8"
            }
            response = requests.post(url, json=data, headers=header)
    return response.json()


# 处理签到时间逻辑
def check_attendance(attends_str):
    # 解析签到时间字符串为分钟数列表
    attend_times = []
    for time_str in attends_str.split(','):
        if time_str.strip():
            hours, minutes = map(int, time_str.split(':'))
            attend_times.append(hours * 60 + minutes)

    # 定义规则时间点（转换为分钟数）
    rules = {
        '08:00': (0, 8 * 60),  # 8:00之前
        '12:00': (12 * 60, 12 * 60 + 30),  # 12:00到12:30
        '13:30': (12 * 60 + 30, 13 * 60 + 30),  # 12:30到13:30
        '17:30': (17 * 30 + 30, 24 * 60)  # 17:30之后
    }

    # 检查每个时间点是否签到
    attended = {time: False for time in rules.keys()}
    for time in attend_times:
        for rule_time, (start, end) in rules.items():
            if start <= time <= end:
                attended[rule_time] = True
                break

    # 收集未签到的时间点
    missing_attendances = [time for time,
                           is_attended in attended.items() if not is_attended]
    return missing_attendances


if __name__ == "__main__":
    # res = qianka_get_kq('000036', '06')
    # print(res)
    qianka_post('040267', ['2025-08-13', '2025-08-12'],
                ["07:48,17:35", "07:55,12:01,17:34"])
